const spawn = require('cross-spawn')
const inquirer = require('inquirer')
const fs = require('fs')
const path = require('path')
const ip = require('ip')
const cwd = process.cwd()
function checkList() {
  const promptList = [
    {
      type: 'rawlist',
      message: '请选择环境',
      pageSize: 100,
      name: 'env',
      choices: [
        {
          name: '测试环境',
          value: 'test'
        },
        {
          name: '预发布环境',
          value: 'pre'
        },
        {
          name: '正式环境',
          value: 'prod'
        }
      ]
    },
    {
      type: 'input',
      message: '请输入端口号（默认8081）：',
      name: 'port',
      default: '8081'
    }
  ]
  return inquirer.prompt(promptList)
}

function chooseEnv() {
  checkList().then((options) => {
    fs.writeFileSync(
      path.join(cwd, '/src/core/env.ts'),
      `/** 该文件为自动生成，用于运行时的环境变量，test | pre | prod */
export const env = '${options.env}'
export const ip = '${ip.address()}'
`,
      { encoding: 'utf8' }
    )
    spawn('npx', ['react-native', 'start', '--port', `${options.port || 8081}`], {
      stdio: 'inherit',
    })
  })
}

module.exports = {
  chooseEnv
}
